import { formatDate } from '@src/assets/js/tool'
import { SeriesSchema, SeriesCaseSchema } from '@src/components/schema/seriesCase'
import { Space, Divider, Modal, message } from 'antd'
import { ColumnsType } from 'antd/es/table'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import { awaitWrap } from '@js/tool'
import { deleteSeriesRequest } from './ajax'
import { Dispatch } from 'redux'
import { addWindow } from '@src/redux/actions/tab'

const { confirm } = Modal

function confirmSubmit (data: SeriesSchema, refreshData: () => void): void {
  confirm({
    icon: <ExclamationCircleOutlined />,
    content: `您确认要解除 ${data.serieno} 吗？`,
    onOk: () => {
      delHandle(data.id, refreshData).catch(e => console.error(e))
    }
  })
}

async function delHandle (id: string, refreshData: () => void): Promise<void> {
  const [e] = await awaitWrap(deleteSeriesRequest(id))
  if (e === null) {
    message.success('解除成功').then(null, null)
    refreshData()
  }
}

export function getColumn (dispatch: Dispatch, t: string, setModifyData: (v: SeriesSchema) => void, setVisible: (v: boolean) => void, refreshData: () => void): ColumnsType<SeriesSchema> {
  const columns: ColumnsType<SeriesSchema> = [
    {
      title: '序号',
      dataIndex: 'orderno',
      key: 'orderno',
      width: 80
    },
    {
      title: '系列号',
      dataIndex: 'serieno',
      key: 'serieno',
      width: 120
    },
    {
      title: '案件数',
      dataIndex: 'case',
      key: 'case',
      render: (v: SeriesCaseSchema[]) => {
        if (v instanceof Array) {
          return v.length
        }
        return 0
      },
      width: 100
    },
    {
      title: '标签',
      dataIndex: 'tag',
      key: 'tag',
      width: 200
    },
    {
      title: '案号',
      dataIndex: 'caseno_info',
      key: 'caseno_info'
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      width: 100
    },
    {
      title: '创建时间',
      dataIndex: 'create_datetime',
      key: 'create_datetime',
      render: (v: number) => {
        if (typeof v === 'number') {
          return formatDate(v, 'YYYY-MM-DD')
        }
      },
      width: 120
    },
    {
      title: '操作',
      dataIndex: 'id',
      key: 'id',
      width: 240,
      render: (v: string, l: SeriesSchema) => {
        return (
          <Space split={<Divider type="vertical" />}>
            <a onClick={() => {
              dispatch(addWindow({ id: `series-case-list-${v}`, title: `${l.serieno}`, componentName: 'SeriesCaseList', forceRefresh: true, meta: {id: v} }))
            }}>详情</a>
            <a onClick={() => { setModifyData(l); setVisible(true) }}>编辑</a>
            <a onClick={() => confirmSubmit(l, refreshData)}>解除</a>
          </Space>
        )
      }
    }
  ]
  return columns
}
